﻿using System;
using System.Windows;

using Microsoft.Phone.Controls;
using PhoneGestureEventArgs = Microsoft.Phone.Controls.GestureEventArgs;

using SSTU.ViewModel;
using SSTU.ViewModel.Item;
using System.Windows.Navigation;

namespace SSTU.View
{
	/// <summary>
	/// Page for main menu with time tables, faculty/group selecting.
	/// </summary>
	public partial class TimeTableMenuPage : PhoneApplicationPage
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="TimeTableMenuPage"/> class.
		/// </summary>
		public TimeTableMenuPage()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Gets or sets the main associated view model.
		/// </summary>
		public TimeTableMenuViewModel ViewModel
		{
			get { return DataContext as TimeTableMenuViewModel; }
			set { DataContext = value; }
		}

		/// <summary>
		/// Called when a page becomes the active page in a frame.
		/// </summary>
		/// <param name="e">An object that contains the event data.</param>
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			if (ViewModel != null)
			{
				ViewModel.Initialize();
			}
		}

		/// <summary>
		/// Called when the faculty item taped.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="Microsoft.Phone.Controls.GestureEventArgs"/> instance containing the event data.</param>
		private void OnFacultyItemTap(object sender, PhoneGestureEventArgs e)
		{
			var departmentItem = ((FrameworkElement)sender).DataContext as FacultyItemVM;
			if ((ViewModel != null) && (departmentItem != null))
			{
				ViewModel.OpenFaculty(departmentItem);
			}
		}

		/// <summary>
		/// Called when the group item taped.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The <see cref="Microsoft.Phone.Controls.GestureEventArgs"/> instance containing the event data.</param>
		private void OnGroupItemTap(object sender, PhoneGestureEventArgs e)
		{
			// When context menu for group item is opened, event may be generated not for the items control item, but for context menu, without data context.
			var originalSource = e.OriginalSource as DependencyObject;
			var contextMenu = ContextMenuService.GetContextMenu(originalSource);
			if ((ViewModel != null) && (contextMenu != null) && !contextMenu.IsOpen)
			{
				var groupItem = ((FrameworkElement)sender).DataContext as GroupItemVM;
				if (groupItem != null)
				{
					ViewModel.OpenGroup(groupItem);
				}
			}
		}
	}
}